﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace 测试多线程卡死情况
{
    /// <summary>
    /// 条码车号对应信息
    /// </summary>
    public class ScannerBacodeInfo
    {
        public byte scannerNumber;
        public int CarNo;
        public int LastCarNo;
        public string Barcode;
        public DateTime DtToDeal;
        public List<string> BarcodeList;
        public int CarNoOffset = -1;
        public List<int> CarNoOffsetList = new List<int>();
        public int LastCarHead = -1;

        /// <summary>
        ///存车头偏移
        /// </summary>
        public Dictionary<int, int> CarOffsetDict = new Dictionary<int, int>();
    }

    class Program
    {
        static void Main(string[] args)
        {
            //启动获取条码线程
            StartDealBarCode(5);

            Thread thread = new Thread(AddBarcose);
            thread.IsBackground = true;
            thread.Start();

            for (int i = 0; i < 10; i++)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(STOSendI2PackageDataThread), null);
            }

            Console.ReadKey();
        }

        static void STOSendI2PackageDataThread(object cI2pkgDataQue)
        {
            while (true)
            {
                try
                {
                    DateTime dateTime = DateTime.Now;
                    int i = 1;
                    while (i <= 3) //最多上传3次
                    {
                        bool bUploadFlags = I2_CommPackageDataReport(3 * 1000);

                        if (bUploadFlags)
                            break;
                        else
                        {
                            
                        }
                        i++;
                    }
                    Console.WriteLine($"**********************************************{DateTime.Now.Subtract(dateTime).TotalMilliseconds}");
                }
                catch (Exception ex)
                {

                }
                Thread.Sleep(200);
            }
        }

        public static bool I2_CommPackageDataReport(int time)
        {
            try
            {
                string url = "data={\"pdaCode\":\"GZ\",\"opTerminal\"}]}";
                string result = OpenReadWithHttps("http://127.0.0.1:8090/branchweb/sortservice?", url, time, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 0), false);
                return false;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        public static string OpenReadWithHttps(string url, string postdata, int timeout, IPEndPoint ip, bool isString)
        {
            HttpWebRequest request = null;
            try
            {
                IPEndPoint m_OutIPEndPoint;
                m_OutIPEndPoint = ip;
                Encoding encoding = Encoding.UTF8;
                request = (HttpWebRequest)WebRequest.Create(url);
                request.Proxy = null;
                request.Timeout = timeout;

                request.CookieContainer = new CookieContainer();
                request.Method = "POST";
                request.Accept = "*/*";
                request.ContentType = "application/json";
                byte[] buffer = encoding.GetBytes(postdata);
                request.ContentLength = buffer.Length;
                request.GetRequestStream().Write(buffer, 0, buffer.Length);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StringBuilder sb = new StringBuilder();
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    const int length = 1024;
                    char[] c = new char[length];
                    int index = reader.Read(c, 0, c.Length);
                    while (index > 0)
                    {
                        var list = c.ToList();
                        list.RemoveAll(c_ => c_ <= 0);
                        c = list.ToArray();
                        sb.Append(c);
                        c = new char[length];
                        index = reader.Read(c, 0, c.Length);
                    }
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                return "网络异常" + ex.Message;
            }
            finally
            {
                if (request != null)
                {
                    request.Abort();
                }
            }
        }

        /// <summary>
        /// 条码列表的信息
        /// </summary>
        private static Queue<ScannerBacodeInfo> ScannerBacodeInfoListQueue = new Queue<ScannerBacodeInfo>();
        private static object ScannerBacodeQueueLock = new object();

        /// <summary>
        /// 处理条码 获取获取分拣口线程
        /// </summary>
        /// <param name="nThreadCount"></param>
        public static void StartDealBarCode(int nThreadCount)
        {
            for (int i = 0; i < nThreadCount; i++)
            {
                new Task(
                    () =>
                    {
                        Console.WriteLine($"线程方法名:StartDealBarCode;线程id:{System.AppDomain.GetCurrentThreadId()}");
                        while (true)
                        {
                            Thread.Sleep(10);
                            try
                            {
                                ScannerBacodeInfo scannerBacodeList = GetScannerBacodeQueue();

                                if (scannerBacodeList == null)
                                    continue;
                                else
                                {
                                    scannerBacodeList.DtToDeal = DateTime.Now;

                                    ThreadPool.QueueUserWorkItem(new WaitCallback(StartDealBarCodeThread), scannerBacodeList);
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(string.Format("返回的下料口有误:{0}", ex.ToString()));
                            }
                        }
                    }
                    , TaskCreationOptions.LongRunning).Start();
            }
        }

        public static void StartDealBarCodeThread(object scannerBacodeInfo)
        {
            try
            {
                DateTime dateTime = DateTime.Now;
                ScannerBacodeInfo scannerBacodeList = (ScannerBacodeInfo)scannerBacodeInfo;
                int carIndex = scannerBacodeList.CarNo;
                List<string> barcodeList = scannerBacodeList.BarcodeList;

                Console.WriteLine(string.Format("准备获取分拣口 耗时:{0},BarCodeThreadid:{1};进入线程耗时:{2}"
       , (DateTime.Now - scannerBacodeList.DtToDeal).TotalMilliseconds, System.AppDomain.GetCurrentThreadId(), (DateTime.Now - dateTime).TotalMilliseconds));

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        static void AddBarcose()
        {
            while (true)
            {
                ScannerBacodeInfo scannerBacodeInfo = new ScannerBacodeInfo();
                scannerBacodeInfo.Barcode = "nobar";
                AddScannerBacodeQueue(scannerBacodeInfo);
                Thread.Sleep(60);
            }
        }

        /// <summary>
        /// 加入队列
        /// </summary>
        /// <param name="scannerBacodeList"></param>
        public static void AddScannerBacodeQueue(ScannerBacodeInfo scannerBacodeList)
        {
            lock (ScannerBacodeQueueLock)
            {
                ScannerBacodeInfoListQueue.Enqueue(scannerBacodeList);
            }
        }


        /// <summary>
        /// 取条码
        /// </summary>
        /// <returns></returns>
        public static ScannerBacodeInfo GetScannerBacodeQueue()
        {
            lock (ScannerBacodeQueueLock)
            {
                if (ScannerBacodeInfoListQueue.Count > 0)
                    return ScannerBacodeInfoListQueue.Dequeue();
                else
                    return null;
            }
        }
    }
}
